package com.xbongbong.crm.perform.query.list.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmListQryService;
import com.xbongbong.crm.handle.analysis.DefaultListAnalysisDataHandler;
import com.xbongbong.crm.perform.query.list.button.ArchivedTag;
import com.xbongbong.crm.perform.query.list.button.Remind;
import com.xbongbong.crm.service.condition.QuotationConditionServiceImpl;
import com.xbongbong.crm.service.impl.QuotationLinkProductServiceImpl;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.parent.explain.HandleExplainHelp;
import com.xbongbong.parent.pojo.list.ConditionListPojo;
import com.xbongbong.parent.pojo.list.ConditionListResultPoJo;
import com.xbongbong.parent.pojo.list.DataAnalysisListPojo;
import com.xbongbong.parent.pojo.list.FieldListPojo;
import com.xbongbong.parent.pojo.list.PermissionListPojo;
import com.xbongbong.parent.util.FieldUtil;
import com.xbongbong.pro.applist.pojo.AppListPojo;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.HandleExplainPojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.pro.message.model.PushModel;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.constant.TabConstant;
import com.xbongbong.saas.enums.TagEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.dictionary.ArchivedEnum;
import com.xbongbong.saas.help.SaasLinkProductHelp;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 报价单列表
 * @author 吴峰
 * @date 2022/06/10 13:52
 */
@Slf4j
@Service("quotationListServiceImpl")
public class QuotationListServiceImpl extends AbstractCrmListQryService {
    @Resource
    private SaasLinkProductHelp saasLinkProductHelp;
    @Resource
    private QuotationConditionServiceImpl quotationConditionService;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private HandleExplainHelp handleExplainHelp;
    @Resource
    private QuotationLinkProductServiceImpl quotationLinkProductService;
    @Resource
    private DefaultListAnalysisDataHandler defaultListAnalysisDataHandler;
    @Resource
    private PushModel pushModel;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;
    @Resource
    private Remind remind;

    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.QUOTATION.getCode());
    }

    @Override
    public List<ConditionsEntityExt> getPermission(PermissionListPojo permissionListPojo) throws XbbException {
        UserVO userVO = permissionListPojo.getUserVO();
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        if (userVO.isMaxDataPermission()){
            return conditionList;
        }

        return getTeamUserPermission(userVO);
    }

    /**
     * 需要根据字段返回字段类型
     * 该方法用于列表页的范围筛选，报价单用范围筛选可选择负责人、协同人，报价人，其中负责人和协同人在调用该方法层已实现，此处无需实现，除非有特殊逻辑
     * @param attr
     * @return
     */
    @Override
    protected Integer getFieldTypeByAttr(String attr) {
        if (Objects.equals(attr, FieldTypeEnum.OWNERID.getAlias())) {
            return FieldTypeEnum.OWNERID.getType();
        }  else if (Objects.equals(attr, FieldTypeEnum.COUSERID.getAlias())) {
            return FieldTypeEnum.COUSERID.getType();
        } else if (Objects.equals(attr, QuotationEnum.QUOTATION_PERSON.getAttr())) {
            return QuotationEnum.QUOTATION_PERSON.getFieldType();
        }
        return 0;
    }

    @Override
    public ConditionListResultPoJo getCondition(ConditionListPojo conditionListPojo) throws XbbException {
        getCommonConditionList(conditionListPojo);

        // 公共筛选
        webCommonFilter(conditionListPojo);
        return new ConditionListResultPoJo(conditionListPojo.getConditionList(), conditionListPojo.getShouldConditionList());
    }

    @Override
    public ConditionListResultPoJo mobileGetCondition(ConditionListPojo conditionListPojo) throws XbbException {
        //  手机端条件封装
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionListPojo.getConditionList(), conditionListPojo.getUserVO(), XbbRefTypeEnum.QUOTATION.getCode(), conditionListPojo.getSubBusinessType(), conditionListPojo.getPlatform());
        // 公共条件封装
        getCommonConditionList(conditionListPojo);
        return new ConditionListResultPoJo(conditionListPojo.getConditionList(), conditionListPojo.getShouldConditionList());
    }

    @Override
    protected void handleFieldAttrEntity(FieldAttrEntity item, FieldListPojo fieldListPojo) {
        super.handleFieldAttrEntity(item, fieldListPojo);
        FieldUtil.packageSelectProductField(item);
    }

    @Override
    public HandleExplainPojo getExplain(FieldListPojo fieldListPojo) throws XbbException {
        try {
            List<String> fieldList = new ArrayList<>();
            List<FieldAttrEntity> explainList = commonGetExplain(fieldListPojo, fieldList);
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO(explainList, fieldListPojo.getForm(), fieldListPojo.getCorpid(), fieldListPojo.getUserVO().getUserId(), fieldListPojo.getUserVO(), true, fieldListPojo.getSubBusinessType());
            HandlerExplainVO handlerExplainVO = handleExplainHelp.handleExplain(handlerExplainDTO);
            HandleExplainPojo handleExplainPojo = new HandleExplainPojo();
            explainList = handlerExplainVO.getHeadList();
            handleExplainPojo.setFieldList(fieldList);
            handleExplainPojo.setExplainList(explainList);
            return handleExplainPojo;
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            log.error("com.xbongbong.crm.list.QuotationListServiceImpl.getExplain error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public List<PaasFormDataEntityExt> webDataAnalysis(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {
        List<PaasFormDataEntityExt> formDataList = dataAnalysisListPojo.getFormDataList();

        FormDataListDTO formDataListDTO = new FormDataListDTO(dataAnalysisListPojo.getCorpid(), dataAnalysisListPojo.getFormId(), dataAnalysisListPojo.getSaasMark(), dataAnalysisListPojo.getBusinessType(), dataAnalysisListPojo.getSubBusinessType(), dataAnalysisListPojo.getDistributorMark(), dataAnalysisListPojo.getUserVO(), dataAnalysisListPojo.getAnalysisAmountOfThousandBitsWithOriginalValue());
        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        formDataListVO.setPaasFormDataESList(formDataList);
        List<FieldAttrEntity> explainList = dataAnalysisListPojo.getExplainList();
        formDataListVO.setHeadList(explainList);
        // 解析关联产品，只有web需要
        quotationLinkProductService.analysisListProductData(formDataListDTO, formDataListVO.getPaasFormDataESList(), formDataListVO.getHeadList(), 1, null);
        defaultListAnalysisDataHandler.analysisDataList(formDataListDTO, formDataListVO);
        defaultListAnalysisDataHandler.analysisAmountOfThousandBits(formDataListVO, dataAnalysisListPojo.getAnalysisAmountOfThousandBitsWithOriginalValue());

        return formDataListVO.getPaasFormDataESList();
    }


    @Override
    public List<AppListPojo> dingtalkOperate(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {
        String corpid = dataAnalysisListPojo.getCorpid();
        List<AppListPojo> resultList = new ArrayList<>();
        List<PaasFormDataEntityExt> dataList =dataAnalysisListPojo.getFormDataList();
        if (CollectionUtils.isEmpty(dataList)) {
            return resultList;
        }
        Integer businessType = dataAnalysisListPojo.getBusinessType();
        List<Long> dataIdIn = new ArrayList<>();
        dataList.forEach(item->{
            dataIdIn.add(item.getId());
        });

        Remind remindPojo = remind.setRemindField( corpid, businessType, dataAnalysisListPojo.getSubBusinessType(), dataIdIn, dataAnalysisListPojo.getExplainList());
        String amount;
        String amountAttr = QuotationEnum.AMOUNT.getAttr();
        String unit = I18nMessageUtil.getMessage(TabConstant.YUAN);
        boolean amountVisible = false;
        for (FieldAttrEntity item : dataAnalysisListPojo.getExplainList()) {
            if (Objects.equals(item.getAttr(), amountAttr)) {
                amountVisible = Objects.equals(item.getVisible(), 1);
                break;
            }
        }

        for (PaasFormDataEntityExt entityExt : dataList) {
            JSONObject data = entityExt.getData();
            Long dataId = entityExt.getDataId();

            JSONObject superScript = new JSONObject();
            JSONObject others = new JSONObject();

            /*-- 角标 -*/
            superScript.put("message", remindPojo.getList().contains(dataId) ? 1 : 0);

            // 归档标志：1代表归档，2代表未归档
            if (Objects.equals(data.getInteger(QuotationEnum.ARCHIVED.getAttr()), 1)) {
                superScript.put("archived", ArchivedEnum.ARCHIVED.getCode());
            }
            /*-- 其他 -*/
            amount = FastJsonHelper.getStringOrDefaultFromFormData(data, amountAttr, "0");
            amount += unit;
            if (!amountVisible) {
                amount = StringConstant.INVISIBLE_VALUE;
            }
            /*-- 其他 -*/
            others.put("amount", amount);


            List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);

            List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);

            List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
            //app系统关联数据展示需要 others 和 superScript
            data.put("others", others);
            data.put("superScript", superScript);

            resultList.add(new AppListPojo(dataId, titleList, summaryList, superScript, lablesList, others, entityExt.getAppId(), entityExt.getMenuId(), entityExt.getFormId()));
        }
        return resultList;
    }

    @Override
    public void webOperate(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {
        List<PaasFormDataEntityExt> dataList =dataAnalysisListPojo.getFormDataList();
        List<FieldAttrEntity> list = dataAnalysisListPojo.getExplainList();
        String corpid = dataAnalysisListPojo.getCorpid();
        List<Long> dataIdIn = new ArrayList<>();
        dataList.forEach(item->{
            dataIdIn.add(item.getId());
        });
        // 提醒
        Remind remindPojo = remind.setRemindField(corpid,  dataAnalysisListPojo.getBusinessType(), dataAnalysisListPojo.getSubBusinessType(), dataIdIn, dataAnalysisListPojo.getExplainList());
        String field = QuotationEnum.QUOTATION_NO.getAttr();
        ArchivedTag archivedTagPojo = new ArchivedTag(field+"Tag");
        list.forEach(item->{
            if (Objects.equals(item.getAttr(), field)) {
                item.setTagAttr(field + "Tag");
            }
        });
        Integer businessType = dataAnalysisListPojo.getBusinessType();
        dataList.forEach(item->{
            // 提醒
            Remind.setRemindData(remindPojo, item);
            JSONObject tagData = item.getTagData();
            JSONObject data = item.getData();
            // 设置“归档”状态
            ArchivedTag.setArchivedData(archivedTagPojo, tagData, Objects.equals(businessType, XbbRefTypeEnum.QUOTATION.getCode()) && Objects.equals(data.getInteger(QuotationEnum.ARCHIVED.getAttr()), 1), TagEnum.TAG_ARCHIVED);
        });
    }



    private List<ConditionsEntityExt> getCommonConditionList(ConditionListPojo conditionListPojo) throws XbbException {
        List<ConditionsEntityExt> list = conditionListPojo.getConditionList() == null ? new ArrayList<>() : conditionListPojo.getConditionList();
        //判断conditionList中是否存在 is_new字段，自定义指标需要查询历史版本数据
        boolean isNewExist = false;
        for (ConditionsEntityExt e : list) {
            if (Objects.equals(QuotationEnum.IS_NEW.getAttr(), e.getAttr()) && Objects.equals(XbbRefTypeEnum.QUOTATION.getCode(), conditionListPojo.getSubBusinessType())) {
                isNewExist = true;
            }
        }
        if(!isNewExist){
            list.addAll(quotationConditionService.handleConditionBySubBusinessType(conditionListPojo));
        }

        conditionListPojo.setConditionList(list);
        setCommonCondition(conditionListPojo);
        // 关联产品筛选
        saasLinkProductHelp.selectProductCondition(list, conditionListPojo.getCorpid());

        return list;
    }

}
